package com.netflix.hystrix;

import java.util.ArrayList;
import java.util.List;

import com.netflix.hystrix.HystrixCommandMetrics.HealthCounts;
import com.netflix.hystrix.strategy.concurrency.HystrixRequestContext;

public class CircuitBreakerTest {

	public static void main(String[] args) throws Exception {

		HystrixRequestContext context = HystrixRequestContext
				.initializeContext();

		final List<Thread> ts = new ArrayList<Thread>();

		int threadCount = 30;
		for (int i = 0; i < threadCount; i++) {
//			Thread t = new MyThread(i, ts);
//			t.start();
			ErrorCommand c = new ErrorCommand();
			c.execute();
			
			// 如果断路器打开，则输出信息
			if(c.isCircuitBreakerOpen()) {
				HystrixCommandMetrics metrics = c.getMetrics();
				// 查看失败率等信息
				HealthCounts hc = metrics.getHealthCounts();
				System.out.println("total: " + hc.getTotalRequests() + ", error: "
						+ hc.getErrorCount() + "---" + i + "---"
						+ c.isCircuitBreakerOpen());
			}
		}
		// 等待全部线程执行结束
//		while (true) {
//			if(false) {
//				break;
//			}
//		}
		context.shutdown();
	}

}

class MyThread extends Thread {

	private int index;
	private List<Thread> ts;

	public MyThread(int index, List<Thread> ts) {
		this.index = index;
		this.ts = ts;
	}

	public void run() {
		ErrorCommand c = new ErrorCommand();
		try {
			c.execute();
		} catch (Exception e) {

		} finally {
			HystrixCommandMetrics metrics = c.getMetrics();
			// 查看失败率等信息
			HealthCounts hc = metrics.getHealthCounts();
			System.out.println("total: " + hc.getTotalRequests() + ", error: "
					+ hc.getErrorCount() + "---" + index + "---"
					+ c.isCircuitBreakerOpen());
			ts.add(this);
		}

	}
}
